package top.broncho.gank.ui.fragment

import android.content.Intent
import android.os.Bundle
import android.view.View
import androidx.fragment.app.viewModels
import androidx.recyclerview.widget.DefaultItemAnimator
import androidx.recyclerview.widget.LinearLayoutManager
import androidx.swiperefreshlayout.widget.SwipeRefreshLayout
import com.chad.library.adapter.base.BaseQuickAdapter
import top.broncho.gank.R
import top.broncho.gank.adapter.KnowledgeTreeAdapter
import top.broncho.gank.bean.KnowledgeTreeBody
import top.broncho.gank.constant.Constant
import top.broncho.gank.databinding.FragmentRefreshLayoutBinding
import top.broncho.gank.ui.activity.KnowledgeActivity
import top.broncho.gank.widget.SpaceItemDecoration
import kotlinx.android.synthetic.main.fragment_refresh_layout.*
import top.broncho.mvvm.base.BaseDiFragment

/**
 * Created by chenxz on 2018/5/8.
 */
class KnowledgeTreeFragment : BaseDiFragment<FragmentRefreshLayoutBinding>() {

    companion object {
        fun getInstance(): KnowledgeTreeFragment = KnowledgeTreeFragment()
    }

    private val viewModel by viewModels<KnowledgeTreeViewModel> { viewModelFactory }

    /**
     * 每页数据的个数
     */
    protected var pageSize = 20

    /**
     * 是否是下拉刷新
     */
    protected var isRefresh = true

    /**
     * LinearLayoutManager
     */
    protected val linearLayoutManager: LinearLayoutManager by lazy {
        LinearLayoutManager(activity)
    }

    /**
     * RecyclerView Divider
     */
    private val recyclerViewItemDecoration by lazy {
        activity?.let {
            SpaceItemDecoration(it)
        }
    }

    /**
     * RefreshListener
     */
    protected val onRefreshListener = SwipeRefreshLayout.OnRefreshListener {
        isRefresh = true
        onRefreshList()
    }

    /**
     * LoadMoreListener
     */
    protected val onRequestLoadMoreListener = BaseQuickAdapter.RequestLoadMoreListener {
        isRefresh = false
        swipeRefreshLayout.isRefreshing = false
        onLoadMoreList()
    }

    /**
     * datas
     */
    private val datas = mutableListOf<KnowledgeTreeBody>()

    /**
     * Adapter
     */
    private val mAdapter: KnowledgeTreeAdapter by lazy {
        KnowledgeTreeAdapter(activity, datas)
    }

    override fun getLayoutId(): Int = R.layout.fragment_refresh_layout
    override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
        super.onViewCreated(view, savedInstanceState)
        initView(view)
        viewModel.article.observe({ lifecycle }) {
            swipeRefreshLayout.isRefreshing = false
            if (it.isFailure) {
                showError(it.exceptionOrNull().toString())
                return@observe
            }
            mLayoutStatusView?.showContent()
            setKnowledgeTree(it.getOrThrow())
        }
    }

    fun initView(view: View) {
        mLayoutStatusView = multiple_status_view

        swipeRefreshLayout.run {
            setOnRefreshListener(onRefreshListener)
        }
        recyclerView.run {
            layoutManager = linearLayoutManager
            itemAnimator = DefaultItemAnimator()
            recyclerViewItemDecoration?.let { addItemDecoration(it) }
        }
        recyclerView.adapter = mAdapter

        mAdapter.run {
            bindToRecyclerView(recyclerView)
            setEnableLoadMore(false)
            onItemClickListener = this@KnowledgeTreeFragment.onItemClickListener
            // setEmptyView(R.layout.fragment_empty_layout)
        }
    }

    override fun onResume() {
        super.onResume()
        if (viewModel.article.value == null) {
            lazyLoad()
        }
    }

    fun lazyLoad() {
        mLayoutStatusView?.showLoading()
        viewModel.requestKnowledgeTree()
    }

    fun onRefreshList() {
        viewModel.requestKnowledgeTree()
    }

    fun onLoadMoreList() {
    }

    fun hideLoading() {
        mAdapter.run {
            loadMoreComplete()
        }
    }

    fun showError(errorMsg: String) {
        mAdapter.loadMoreFail()
    }

    fun scrollToTop() {
        recyclerView.run {
            if (linearLayoutManager.findFirstVisibleItemPosition() > 20) {
                scrollToPosition(0)
            } else {
                smoothScrollToPosition(0)
            }
        }
    }

    fun setKnowledgeTree(lists: List<KnowledgeTreeBody>) {
        lists.let {
            mAdapter.run {
                replaceData(lists)
            }
        }
        if (mAdapter.data.isEmpty()) {
            mLayoutStatusView?.showEmpty()
        } else {
            mLayoutStatusView?.showContent()
        }
    }

    /**
     * ItemClickListener
     */
    private val onItemClickListener = BaseQuickAdapter.OnItemClickListener { _, _, position ->
        if (datas.size != 0) {
            val data = datas[position]
            Intent(activity, KnowledgeActivity::class.java).run {
                putExtra(Constant.CONTENT_TITLE_KEY, data.name)
                putExtra(Constant.CONTENT_DATA_KEY, data)
                startActivity(this)
            }
        }
    }

}